package main

import (
	"context"
	"embed"
	"log"
	"os"
	"qrsj-collect/backend/app"

	"github.com/joho/godotenv"
	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/options"
	"github.com/wailsapp/wails/v2/pkg/options/assetserver"
	"github.com/wailsapp/wails/v2/pkg/options/windows"
)

//go:embed all:frontend/dist
var assets embed.FS

//go:embed .env
var envFile string

func loadEnv() error {
	envMap, err := godotenv.Unmarshal(envFile)
	if err != nil {
		return err
	}
	for key, value := range envMap {
		if err := os.Setenv(key, value); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	err := loadEnv()
	if err != nil {
		log.Fatalf("Error loading .env file: %v", err)
	}
	file, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	log.SetOutput(file)

	// Create an instance of the app structure
	mainApp := app.NewMainApp()
	clipboardApp := app.NewClipboard()
	updateApp := app.NewUpdateApp()
	serverApp := app.NewServerApp()
	hotkeyApp := app.NewHotkeyApp()

	// Create application with options
	err = wails.Run(&options.App{
		Title:     "小助手",
		Width:     800,
		Height:    600,
		MinWidth:  200,
		MinHeight: 200,
		// DisableResize: true,
		Frameless: true,
		AssetServer: &assetserver.Options{
			Assets: assets,
		},
		BackgroundColour: options.NewRGBA(255, 255, 255, 0),
		Bind: []interface{}{
			mainApp,
			clipboardApp,
			updateApp,
			serverApp,
			hotkeyApp,
		},
		OnStartup: func(ctx context.Context) {
			mainApp.Startup(ctx)
			clipboardApp.Startup(ctx)
			updateApp.Startup(ctx)
			serverApp.Startup(ctx)
			hotkeyApp.Startup(ctx)
		},
		OnDomReady: func(ctx context.Context) {
			// serverApp.DomReady(ctx)
		},
		OnShutdown: func(ctx context.Context) {
			mainApp.Shutdown(ctx)
			clipboardApp.Shutdown(ctx)
			serverApp.Shutdown(ctx)
			hotkeyApp.Shutdown(ctx)
		},
		OnBeforeClose: nil,
		Windows: &windows.Options{
			WebviewIsTransparent: true,
			WindowIsTranslucent:  true,
			BackdropType:         windows.Acrylic,
			DisableWindowIcon:    true,
			// Theme:                windows.SystemDefault,
		},
	})

	if err != nil {
		println("Error:", err.Error())
	}
}
